package com.rememberme;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.business.ReminderBus;
import com.dataobject.MyReminder;

public class RemindEditor extends Activity implements OnClickListener {
	// ---------- ---------- ---------- ---------- ----------
	// VARIABLES
	// ---------- ---------- ---------- ---------- ----------
	TimePickerDialog timePickerDialog;
	DatePickerDialog datePickerDialog;
	Calendar dateTimeAlarm = Calendar.getInstance(Locale.getDefault());
	MyReminder mr;
	MyReminder mr_old;
	ReminderBus _Bus;
	private String[] pics = new String[] { "ico_anniversary", "ico_birthday",
			"ico_call", "ico_meeting", "ico_memo", "ico_reminder", "ico_test" };
	private static int index = 0;
	private final String tone_def = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();

	Intent intent;
	ImageButton imgIco;
	EditText txtTitle;
	EditText txtContent;
	Button btnDateTime;
	Button btnAlarm;
	TextView lblTone;
	Button btnTone;
	Button btnSave;

	// ---------- ---------- ---------- ---------- ----------
	// VARIABLES
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// ON-CREATE
	// ---------- ---------- ---------- ---------- ----------
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.remind_editor);
		_Bus = new ReminderBus(this);
		intent = getIntent();
		imgIco = (ImageButton) findViewById(R.id.imageButton);
		txtTitle = (EditText) findViewById(R.id.txtTitle);
		txtContent = (EditText) findViewById(R.id.txtContent);
		btnDateTime = (Button) findViewById(R.id.btnDate);
		btnAlarm = (Button) findViewById(R.id.btnAlarmType);
		lblTone = (TextView) findViewById(R.id.lblAlarmTone);
		btnTone = (Button) findViewById(R.id.btnAlarmTone);
		btnSave = (Button) findViewById(R.id.btnSave);

		imgIco.requestFocus();
		if (intent.getBooleanExtra("isNew", true)) {
			mr = new MyReminder();
			imgIco.setImageDrawable(getResources().getDrawable(
					getResources().getIdentifier(pics[index], "drawable",
							getPackageName())));
			mr.set_Ico(pics[index]);
			mr.set_DateTime(Calendar.getInstance().getTimeInMillis());
			btnDateTime.setText(convertDateToString(Calendar.getInstance(Locale
					.getDefault())));
		} else {
			mr_old = new MyReminder(intent.getIntExtra("id", -1),
					intent.getStringExtra("ico"),
					intent.getStringExtra("title"),
					intent.getStringExtra("content"), intent.getLongExtra(
							"datetime", -1), intent.getStringExtra("alarm"),
					intent.getStringExtra("tone"));
			mr = new MyReminder(mr_old);
			index = getIdFromIcon(mr_old.get_Ico());
			imgIco.setImageDrawable(getResources().getDrawable(
					getResources().getIdentifier(mr_old.get_Ico(), "drawable",
							getPackageName())));
			txtTitle.setText(mr_old.get_Title());
			txtContent.setText(mr_old.get_Content());
			btnDateTime.setText(convertDateToString(mr_old.get_DateTime()));
			btnAlarm.setText(mr_old.get_Alarm());
			if (!mr_old.get_Alarm().equals(
					getResources().getString(R.string.alarm_silent))) {
				lblTone.setVisibility(View.VISIBLE);
				btnTone.setVisibility(View.VISIBLE);
				if (mr_old.get_Tone().equals(getResources().getString(R.string.tone_default))){
					btnTone.setText(getResources().getString(R.string.tone_default));
				} else {
					btnTone.setText(mr_old.get_Tone());
				}
			}
		}

		imgIco.setOnClickListener(this);
		btnDateTime.setOnClickListener(this);
		btnAlarm.setOnClickListener(this);
		btnTone.setOnClickListener(this);
		btnSave.setOnClickListener(this);
	}

	// ---------- ---------- ---------- ---------- ----------
	// ON-CREATE
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// ON-BACK-PRESSED
	// ---------- ---------- ---------- ---------- ----------
	private static boolean doubleBackToExitPressedOnce = false;

	@Override
	public void onBackPressed() {
		if (doubleBackToExitPressedOnce) {
			super.onBackPressed();
			return;
		}
		RemindEditor.doubleBackToExitPressedOnce = true;
		Toast.makeText(this, "Ấn phím BACK lần nữa\nđể quay lại không lưu.",
				Toast.LENGTH_SHORT).show();
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				doubleBackToExitPressedOnce = false;
			}
		}, 2000);
	}

	// ---------- ---------- ---------- ---------- ----------
	// ON-BACK-PRESSED
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// ON-CLICK-LISTENER
	// ---------- ---------- ---------- ---------- ----------
	@Override
	public void onClick(View v) {
		if (v.equals(imgIco)) {
			index = (++index) % pics.length;
			mr.set_Ico(pics[index]);
			imgIco.setImageDrawable(getResources().getDrawable(
					getResources().getIdentifier(pics[index], "drawable",
							getPackageName())));
		} else if (v.equals(btnDateTime)) {
			CustomDateTimePicker customDateTimePicker = initDateTimePicker();
			customDateTimePicker.showDialog();

		} else if (v.equals(btnAlarm)) {
			Dialog dialog = initAlarmPicker();
			dialog.show();

		} else if (v.equals(btnTone)) {

			Dialog dialog = initTonePicker();
			dialog.show();

		} else if (v.equals(btnSave)) {
			if (mr.get_DateTime().before(Calendar.getInstance())){
				Toast.makeText(getApplicationContext(), "Đã quá hạn ngày/giờ", Toast.LENGTH_SHORT).show();
				return;
			}				
			mr.set_Title(txtTitle.getText().toString());
			mr.set_Content(txtContent.getText().toString());
			if (intent.getBooleanExtra("isNew", true)) {
				CallAlarm(mr);
				_Bus.insert(mr);
				finish();
				return;
			}
			if (!mr.equals(mr_old)) {
				_Bus.updateReminder(mr);
				finish();
				return;
			}

		}
	}

	// ---------- ---------- ---------- ---------- ----------
	// ON-CLICK-LISTENER
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// ON_ACTIVITY_RESULT
	// ---------- ---------- ---------- ---------- ----------
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		String theFilePath = new String();
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case 1002:
				theFilePath = data.getData().toString();				
				break;
			case 1003:
				theFilePath = data.getDataString();
				break;
			}
			mr.set_Tone(theFilePath);
			btnTone.setText(theFilePath);
		}
		mr.set_Tone(getResources().getString(R.string.tone_default));
	}

	// ---------- ---------- ---------- ---------- ----------
	// ON_ACTIVITY_RESULT
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// DATE-TIME-PICKER_DIALOG
	// ---------- ---------- ---------- ---------- ----------
	private CustomDateTimePicker initDateTimePicker() {
		CustomDateTimePicker customDateTimePicker = new CustomDateTimePicker(
				this, new CustomDateTimePicker.ICustomDateTimeListener() {

					@Override
					public void onSet(Dialog dialog, Calendar calendarSelected,
							Date dateSelected, int year, String monthFullName,
							String monthShortName, int monthNumber, int date,
							String weekDayFullName, String weekDayShortName,
							int hour24, int hour12, int min, int sec,
							String AM_PM) {
						btnDateTime.setText(calendarSelected
								.get(Calendar.DAY_OF_MONTH)
								+ "/"
								+ (monthNumber + 1)
								+ "/"
								+ year
								+ ", "
								+ hour12 + ":" + min + " " + AM_PM);
						mr.get_DateTime().set(year, monthNumber, date, hour24,
								min);
					}

					@Override
					public void onCancel() {

					}
				});
		customDateTimePicker.set24HourFormat(false);
		customDateTimePicker.setDate(mr.get_DateTime().getTime());
		customDateTimePicker.setTimeIn12HourFormat(
				mr.get_DateTime().get(Calendar.HOUR),
				mr.get_DateTime().get(Calendar.MINUTE),
				mr.get_DateTime().get(Calendar.AM_PM) == 0 ? false : true);
		return customDateTimePicker;
	}

	// ---------- ---------- ---------- ---------- ----------
	// DATE-TIME-PICKER_DIALOG
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// ALARM_DIALOG
	// ---------- ---------- ---------- ---------- ----------
	public Dialog initAlarmPicker() {
		AlertDialog.Builder builder = new Builder(RemindEditor.this);
		final String[] alarm_arr = getResources().getStringArray(
				R.array.alarm_arr);
		builder.setTitle(getResources().getString(R.string.alarm_select))
				.setItems(alarm_arr, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int pos) {
						// TODO Auto-generated method stub
						mr.set_Alarm(alarm_arr[pos]);
						btnAlarm.setText(alarm_arr[pos]);
						if (alarm_arr[pos].equals(getResources().getString(
								R.string.alarm_silent))) {
							lblTone.setVisibility(View.GONE);
							btnTone.setVisibility(View.GONE);
							mr.set_Tone(null);
						} else {
							lblTone.setVisibility(View.VISIBLE);
							btnTone.setVisibility(View.VISIBLE);
							btnTone.setText(getResources().getString(
									R.string.tone_default));
							mr.set_Tone(tone_def);
						}
						dialog.dismiss();
					}
				});
		return builder.create();
	}

	// ---------- ---------- ---------- ---------- ----------
	// ALARM_DIALOG
	// ---------- ---------- ---------- ---------- ----------

	// ---------- ---------- ---------- ---------- ----------
	// TONE_DIALOG
	// ---------- ---------- ---------- ---------- ----------
	public Dialog initTonePicker() {
		AlertDialog.Builder builder = new Builder(RemindEditor.this);
		final String[] tone_arr = getResources().getStringArray(
				R.array.tone_arr);
		builder.setTitle(getResources().getString(R.string.tone_select))
				.setItems(tone_arr, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int pos) {
						//btnTone.setText(tone_arr[pos]);
						if (tone_arr[pos].equals(getResources().getString(
								R.string.tone_default))) {
							btnTone.setText(getResources().getString(R.string.tone_default));
							mr.set_Tone(tone_def);
						} else if (tone_arr[pos].equals(getResources()
								.getString(R.string.tone_collection))) {
							Intent intent = new Intent();
							intent.setType("audio/*");
							intent.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(
									Intent.createChooser(intent, "Duyệt tìm"),
									1002);

						} else {
							Intent recordIntent = new Intent(
									MediaStore.Audio.Media.RECORD_SOUND_ACTION);
							startActivityForResult(recordIntent, 1003);
						}
						dialog.dismiss();
					}
				});
		return builder.create();
	}

	// ---------- ---------- ---------- ---------- ----------
	// TONE_DIALOG
	// ---------- ---------- ---------- ---------- ----------
	private String convertDateToString(Calendar c) {
		return c.get(Calendar.DAY_OF_MONTH) + "/" + (c.get(Calendar.MONTH) + 1)
				+ "/" + c.get(Calendar.YEAR) + ", " + c.get(Calendar.HOUR)
				+ ":" + c.get(Calendar.MINUTE) + " "
				+ new String(c.get(Calendar.AM_PM) == 0 ? "AM" : "PM");
	}

	private int getIdFromIcon(String str) {
		for (int i = 0; i < pics.length; i++) {
			if (pics[i].equals(str)) {
				return i;
			}
		}
		return -1;
	}
	
	private void CallAlarm(MyReminder mr){
		Intent intent = new Intent(getApplicationContext(), InvokedToAlarm.class);
		intent.putExtra("ico", mr.get_Ico());
		intent.putExtra("title", mr.get_Title());
		intent.putExtra("content", mr.get_Content());
		intent.putExtra("alarm", mr.get_Alarm());
		intent.putExtra("tone", mr.get_Tone());
		PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
		AlarmManager alarmManager = (AlarmManager)getBaseContext().getSystemService(ALARM_SERVICE);
		alarmManager.set(AlarmManager.RTC_WAKEUP, mr.get_DateTime().getTimeInMillis(), operation);
	}
}
